﻿using Aliyun.OSS;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Linq;
using TemplateTool.ConvertExtension;

namespace TemplateTool.OSS
{
    public class OSSProvider : IOSS
    {
        private readonly OssConfig _ossConfig;
        private readonly OssClient _ossClient;
        private readonly ILogger<OSSProvider> _logger;
        public OSSProvider(IOptions<OssConfig> options, ILogger<OSSProvider> logger)
        {
            _ossConfig = options.Value;
            _ossClient = new OssClient(_ossConfig.Endpoint, _ossConfig.AccessKeyId, _ossConfig.AccessKeySecret);
            _logger = logger;
        }
        public DeleteObjectResult DeleteObject(string objectName)
        {
            var result = _ossClient.DeleteObject(_ossConfig.BucketName, objectName);

            _logger.LogInformation($"删除文件{_ossConfig.BucketName + _ossConfig.Exampledir}：{objectName}");

            return result;
        }
        public DeleteObjectsResult DeleteObjects(List<string> keys, bool quiet = false)
        {
            var deleteObjectsRequest = new DeleteObjectsRequest(_ossConfig.BucketName, keys, quiet);

            var result = _ossClient.DeleteObjects(deleteObjectsRequest);

            _logger.LogInformation($"批量删除文件{_ossConfig.BucketName + _ossConfig.Exampledir}：{keys.ToJson()}");

            return result;

        }
        public ObjectListing ListObjects(string prefix)
        {
            var url = _ossConfig.Exampledir + prefix + "/";

            var result = _ossClient.ListObjects(_ossConfig.BucketName, url);

            _logger.LogInformation($"列举所有文件{_ossConfig.BucketName + url}：{result.ObjectSummaries.Select(a => a.Key).ToJson()}");

            return result;
        }
    }
}
